package com.dkd.handler;

import cn.elegent.ac.ACHandler;
import cn.elegent.ac.annotation.Topic;
import com.dkd.config.TopicConfig;
import com.dkd.contract.SupplyContract;
import com.dkd.feign.VMService;
import com.dkd.http.vo.TaskViewModel;
import com.dkd.service.TaskService;
import com.dkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author DiXiaoNie
 * @since 2023/2/2 17:44
 */
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements ACHandler<SupplyContract> {
    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String topic, SupplyContract supplyContract) throws Exception {
        try {
            //1.解析协议内容
            if (supplyContract == null) {
                return;
            }
            //2.找出被指派人
            VmVO vmInfo = this.vmService.getVMInfo(supplyContract.getInnerCode());
            if (vmInfo == null) {
                return;
            }
            var userId = this.taskService.getLeastUser(vmInfo.getRegionId(), false);
            if (userId == 0) {
                return;
            }
            //3.构建工单对象
            TaskViewModel taskViewModel = this.taskService.buildTaskViewModel(userId, supplyContract);
            //4.创建工单
            this.taskService.createTask(taskViewModel);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错：" + e.getMessage());
        }
    }
}
